<template>
    <div>
        <div class="content">
            <div class="photoBox">
                <div class="workPhotoList">
                    <div class="onePhoto" v-for="(item, index) in list" :key="index">
                        <img @click="previewImage(index)" :src="item" alt="">
                        <span class="deleteIcon" @click="delImg(index)">
                            <img src="@/assets/img/delete.png" alt="">
                        </span>
                    </div>
                </div>
                <div class="upload">
                    <img  @click="chooseImage" src="@/assets/img/camera.png" alt="">
                </div>
            </div>
        </div>
        <!-- <div>{{access_token}}</div>
        <div>{{list}}</div>
        <div>{{listCopy}}</div>
        <img v-for="item in listCopy" :src="item" alt="" srcset=""> -->
    </div>
</template>
<script>
import {getAccessToken, uploadWechatImg} from '@/api/commonApi'
export default {
    computed: {
      access_token () {
          return this.$store.state.common.access_token
      }
    },
    data () {
        return {
            
            list: [],
            listCopy: [],
            serverIds: [],
            testImg: require('@/assets/logo.png')
        }
    },
    methods: {
        // 选择图片
        chooseImage(){
            if (this.list.length >= 9) {
                this.$toast.fail('最多选择9张图片')
                return
            }
            var count = 9 - this.list.length
         
            return new Promise((resolve, reject) => {
                
                wx.chooseImage({
                    count: count, // 默认9
                    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
                    success: (res) => {

                        var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                        console.log('chooseImage success:::',localIds)
                        this.list = this.list.concat(localIds)  

                        resolve()
                    }
                });
            })
           
        },
        // 启动上传图片
        async startUploadImage () {
           
            if (this.list.length == 0) {
         
                return
            }
            
            this.serverIds = []
            
            for (let item of this.list) {
                
                await this.uploadImage(item)
                
            }
             
        },
        // 将图片上传到微信
        uploadImage(localId){
            
            return new Promise((resolve, reject) => {
                
            
                wx.uploadImage({
                    localId: localId,
                    isShowProgressTips: 0,
                    success:  (res) => {
                        var serverId = res.serverId; // 返回图片的服务器端ID
                        //其他对serverId做处理的代码
                        this.serverIds.push(serverId)
                        
                        resolve()
                    }
                })
            })
            
        },
        // 从微信下载图片到自己的服务器
        async uploadServeId(){
           
            var schoolId = 'agency123456'
            
            let access_token = await this.$store.dispatch('common/getAccessToken')
          
           
            
            let listCopy = [].concat(this.list)
         
            for(let i = 0;i<this.serverIds.length;i++){
                    let res = ''
                    try {
                        res = await uploadWechatImg({
                            schoolId:schoolId,
                            access_token:access_token,
                            media_id:this.serverIds[i]
                        })
                    } catch (error) {
                        
                        console.log('error:', error)
                    }
                    
                    if(res.data){
                        
                        listCopy.splice(i, 1, res.data.replace('http:', 'https:'))
                    }else{
                        // res.media_id = state.serverIds[i]
                        
                        listCopy.splice(i, 1, this.testImg)
                    }
                
            }
            this.listCopy = listCopy
            return listCopy
            
        },
        
        previewImage (index) {
            wx.previewImage({
                current: this.list[index], 
                urls: this.list
            })
        },

        
        // 删除图片
        delImg(index){
            this.list.splice(index,1)
        },
        async upload () {
            var loading =  this.$toast.loading({
                message: '加载中...',
                forbidClick: true,
                type:'loading',
                duration:0
            })
            await this.startUploadImage()
            
            let array = await this.uploadServeId()
            console.log(array)
            loading.clear()
            return array
        },
        clear () {
            this.list = []
            this.listCopy = []
            this.serverIds = []
        }
    },
    destroyed () {
        console.log('media destroyed...')
    }
}
</script>
<style scoped>
    /* .content{
       padding: 0.3rem 0.24rem 0 0.24rem;
    } */
    .photoBox{
        overflow: hidden;
        position: relative;
        min-height: 1rem;
    }
    .workPhotoList{
        margin-top: 0.3rem;
        float: left;
    }
    .onePhoto{
        position: relative;
        width: 1.2rem;
        height: 1.2rem;
        border-radius: 0.08rem;
        margin:0 0.3rem  0.3rem 0;
        display: inline-block;
    }
    .onePhoto img{
        width: 100%; 
        height: 100%; 
        object-fit: cover;
    }
    .deleteIcon{
        position: absolute;
        top: -0.2rem;
        right: -0.2rem;
        display: inline-block;
        width: 0.4rem;
        height: 0.4rem;
        line-height: 0.4rem;
        border-radius: 50%;
        background: rgba(0,0,0,0.3);
        color: #FFF;
        text-align: center;
        z-index: 101;
    }
    .upload{
        width: 0.56rem;
        height: 0.48rem;
        position: absolute;
        top: 0.3rem;
        right: 0;
    }
    .upload img{
        width: 100%;
        height: 100%;
    }
</style>
